﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// add
using System.Xml;
using System.IO;


namespace FormBase
{
    public class XMLKeyValueReading
    {
        string msError;
        public string Error { get { return msError; } }

        /// <summary>
        /// Example "C:\Temp\test1.xml"
        /// </summary>
        public string FullPathFile { get; set; }

        /// <summary>
        /// Example: "/Root/Section1"
        /// </summary>
        public string RootNode { get; set; }

        XmlDocument mXML1 = new XmlDocument();
        public string Key { get; set; }
        public string Value { get { return msValue; } }
        string msValue;
        public string KeyFullPath { get { return RootNode + "/" + Key; } }


        public XMLKeyValueReading()
        {
            FullPathFile = @".\App_Code\Project.xml";
            RootNode = @"/Root/Section1";
        }

        public bool LoadFile()
        {
            if (!File.Exists(FullPathFile))
            {
                msError = "File not found. File=" + FullPathFile;
                return false;
            }
            try
            {
                mXML1.Load(FullPathFile);
            }
            catch (Exception ex)
            {
                msError = ex.Message;
                return false;
            }
            return true;
        }

        public bool ReadKey(string sKey)
        {
            string sQuery;
            XmlNodeList List1;
            XmlElement e1;

            if (mXML1 == null)
            {
                msError = "Please load file first.";
                return false;
            }

            sQuery = string.Format("{0}/Key[@ID='{1}']", RootNode, sKey);
            List1 = mXML1.SelectNodes(sQuery);
            if ((List1 == null) || (List1.Count < 1))
            {
                msError = "Key not found. key=" + sQuery;
                return false;
            }
            e1 = (XmlElement)List1[0];
            msValue = e1.InnerText;
            return true;
        }
     }
}
